define(['jquery', 'frontend/loginpop'], function ($, LoginPop) {

    //黑板
    var Controller = {
        //科目ID
        subject_class_id: 0,
        //附件ID
        attachement_id: 0,
        //画笔类型
        whiteboard_drawtype: "pencil",
        //画布
        canvas: null,
        //画布的父元素
        canvas_parent: null,
        //画布上下文
        ctx: null,
        //铅笔的坐标数组
        points: [],
        //铅笔的文字字号大小
        fontSize: 30,
        //铅笔是否正在输出
        isDrawing: false,

        //打开黑板
        openWhiteboardWindow: function () {
            //没有登陆
            if (LoginPop.logined == 0) {
                LoginPop.openLoginWindow()
                return false;
            }

            if ($(".whiteboard-body").css("display") == "block") {
                Controller.isDrawing = false
                Controller.autoLoadWhiteBoardImage();
            }
        },
        //自动加载白板图片
        autoLoadWhiteBoardImage: function () {
            $.ajax({
                url: '/index/classroom/loadWhiteboard',
                type: 'post',
                data: {
                    subject_class_id: Controller.subject_class_id,
                    attachement_id: Controller.attachement_id
                }, // 发送到服务器的数据
                success: function (json) {
                    console.log(json);
                    Controller.ctx.clearRect(0, 0, Controller.canvas.width, Controller.canvas.height);
                    if (json.code == 1) {
                        var base64Image = json.data.whiteboard;
                        var img = new Image();
                        img.onload = function () {
                            Controller.ctx.drawImage(img, 0, 0, Controller.canvas.width, Controller.canvas.height);
                        };
                        img.src = base64Image;
                    }
                }
            });
        },
        //自动保存图片
        autoSaveWhiteBoardImage: function () {
            var base64Img = Controller.canvas.toDataURL('image/png');
            $.ajax({
                url: '/index/classroom/saveWhiteboard',
                type: 'post',
                data: {
                    subject_class_id: Controller.subject_class_id,
                    attachement_id: Controller.attachement_id,
                    whiteboard: base64Img,
                },
                success: function (json) {
                    console.log(json);
                }
            });
        },
        //初始化
        init: function () {

            //监听Escape按下
            document.addEventListener('keydown', function (event) {
                if (event.key === 'w' && event.altKey) {

                    console.log('按下了复合键，打开黑板');

                    setTimeout(function(){
                        $(".whiteboard-body").show();
                    },20);
                }
                if (event.key === "Escape" || event.keyCode === 27) {
                    if ($(".whiteboard-body").css("display") == "block") {
                        console.log('打开了黑板，关闭它');

                        //自动保存一下
                        Controller.autoSaveWhiteBoardImage();

                        setTimeout(function(){
                            $(".whiteboard-body").hide();
                        },20);
                    }
                }
            });


            $(".online-whiteboard").click(function () {

                //如果没有登陆,就弹出登陆窗口
                if (LoginPop.logined == 0) {
                    LoginPop.openLoginWindow()
                    return false;
                }

                $(".whiteboard-body").css("display") == "block" ? $(".whiteboard-body").css("display", "none") : $(".whiteboard-body").css("display", "block");

                Controller.openWhiteboardWindow();
            })

            // 获取画布和绘画工具
            Controller.canvas = document.getElementById('whiteboard-canvas');
            Controller.canvas_parent = document.getElementById('mid-body-top');

            //设置画布和布景一样大
            Controller.canvas.width = Controller.canvas_parent.offsetWidth - 1;
            Controller.canvas.height = Controller.canvas_parent.offsetHeight - 1;

            // 跟踪绘画状态
            Controller.ctx = Controller.canvas.getContext('2d');
            Controller.ctx.lineJoin = 'round';
            Controller.ctx.lineCap = 'round';
            // 设置全局透明度
            // Controller.ctx.globalAlpha = 0.5;
            // Controller.ctx.filter = 'blur(5px)';

            $(".whiteboard-drawtype").click(function () {
                $(".whiteboard-drawtype").removeClass("whiteboard-drawtype-focus");
                $(this).addClass("whiteboard-drawtype-focus");
                Controller.whiteboard_drawtype = $(this).attr("whiteboard-drawtype");
            });

            $(".whiteboard-eraser").click(function () {
                if (confirm("清空黑板吗？")) {
                    Controller.ctx.clearRect(0, 0, Controller.canvas.width, Controller.canvas.height);
                    Controller.autoSaveWhiteBoardImage();
                }
            });

            // 鼠标单击
            Controller.canvas.onclick = function (e) {
                if (Controller.whiteboard_drawtype != "pencil") {
                    return;
                }
                Controller.points = [];
                Controller.penType(e.offsetX, e.offsetY);
            };

            Controller.canvas.addEventListener('mousedown', Controller.startDrawing)
            Controller.canvas.addEventListener('mousemove', Controller.draw)
            Controller.canvas.addEventListener('mouseup', Controller.stopDrawing)
            Controller.canvas.addEventListener('mouseout', Controller.stopDrawing)
        },
        //用键盘写字
        penType: function (mousex, mousey) {
            Controller.points.push({ x: mousex, y: mousey });
            Controller.typeText();
            Controller.ctx.stroke();
            Controller.points.slice(0, 1);
        },
        //用键盘写字
        typeText: function () {
            const startX = Controller.points[0].x;
            const startY = Controller.points[0].y;

            const textarea = document.createElement('textarea'); // 创建一个多行输入框元素 
            // const textarea = document.createElement('input'); // 创建一个单行输入框元素 
            const canvasRect = Controller.canvas.getBoundingClientRect(); // 获取画布的位置信息

            textarea.rows = 1;
            textarea.style.position = 'absolute';
            // textarea.style.left = (canvasRect.left + startX) - 10 + 'px'; // 计算输入框的左边距（最后-10是为了让光标能显示在鼠标前面一点点）
            textarea.style.left = (canvasRect.left + startX) + 'px'; // 计算输入框的左边距（最后-10是为了让光标能显示在鼠标前面一点点）
            textarea.style.top = (canvasRect.top + startY) + 'px'; // 计算输入框的上边距
            textarea.style.border = '1px solid #000';
            // textarea.style.background = 'transparent';
            textarea.style.backgroundColor = '#000';
            textarea.style.font = Controller.fontSize + 'px 微软雅黑';
            textarea.style.color = '#fff';
            textarea.style.outline = 'none';
            textarea.style.padding = '0';
            textarea.style.margin = '0';
            textarea.style.width = 'auto';
            textarea.style.minHeight = Controller.fontSize + 'px';
            textarea.style.lineHeight = Controller.fontSize + 'px';
            textarea.style.resize = 'none';
            textarea.style.overflow = 'hidden';

            //回车回行
            textarea.addEventListener('keydown', function (event) {
                if (event.keyCode == 13) {
                    textarea.rows += 1;
                    textarea.focus(); // 让输入框获得焦点
                }
            });

            // 监听失去焦点事件
            textarea.addEventListener('blur', function () {
                const text = textarea.value;
                if (text.length > 0) {
                    Controller.ctx.font = Controller.fontSize + 'px 微软雅黑';
                    Controller.ctx.fillStyle = '#000';
                    const lines = text.split('\n'); // 将输入的文本按换行符分割成多行
                    let y = startY;
                    lines.forEach(function (line) {
                        // ctx.fillText(line, startX, y); // 在画布上绘制每一行文字
                        // y += (Controller.fontSize + 5); // 每行文字的垂直间距为35像素（这个一般要根据字体大小进行设置，我设置的是字体大小+5比较合适）
                        Controller.ctx.fillText(line, startX, y + 25);
                        y += (Controller.fontSize);
                    });
                    // ctx.fillText(text, startX - 10, startY + 25); // 在画布上绘制每一行文字

                    Controller.autoSaveWhiteBoardImage();//自动保存
                }
                document.body.removeChild(textarea); // 移除输入框元素
            });

            document.body.appendChild(textarea); // 将输入框元素添加到页面中
            textarea.focus(); // 让输入框获得焦点

        },
        //用笔刷开始绘画
        startDrawing: function (e) {
            if (Controller.whiteboard_drawtype != "brush") {
                return;
            }
            Controller.isDrawing = true
            Controller.draw(e)
        },
        //笔刷结束绘画
        stopDrawing: function () {
            Controller.isDrawing = false
            Controller.ctx.beginPath() // Reset the path for the next draw
        },
        //笔刷绘画中
        draw: function draw(e) {
            if (!Controller.isDrawing) return

            Controller.ctx.lineWidth = 5
            Controller.ctx.lineCap = 'round'
            Controller.ctx.strokeStyle = '#000'

            Controller.ctx.lineTo(e.offsetX, e.offsetY)
            Controller.ctx.stroke()
            Controller.ctx.beginPath()
            Controller.ctx.moveTo(e.offsetX, e.offsetY)

            Controller.autoSaveWhiteBoardImage();//自动保存
        }

    };
    return Controller;
});
